using System;
using System.Collections.Specialized;
using System.Text;
using System.Web;
using Be.Timvw.Framework.Collections;

namespace Be.Timvw.Framework.Web
{
    public static class UriHelper
    {
        private const string NameValueSeparator = "=";
        private const string PairSeparator = "&";
        private const string QuerySeparator = "?";

        public static Uri AddParameters(Uri uri, NameValueCollection additionalParameters, DuplicateKeyBehavior behavior)
        {
            NameValueCollection parameters = new NameValueCollection(HttpUtility.ParseQueryString(uri.Query));
            NameValueCollectionHelper.Add(parameters, additionalParameters, behavior);

            StringBuilder uriBuilder = new StringBuilder();
            uriBuilder.Append(uri.GetLeftPart(UriPartial.Path));

            if(parameters.Count > 0)
            {
                uriBuilder.Append(QuerySeparator);
                uriBuilder.Append(BuildParameterString(parameters));
            }

            uriBuilder.Append(uri.Fragment);

            return new Uri(uriBuilder.ToString());
        }

        public static string BuildParameterString(NameValueCollection parameters)
        {
            StringBuilder parameterStringBuilder = new StringBuilder();

            if (parameters != null)
            {
                foreach (string key in parameters.Keys)
                {
                    string[] values = parameters.GetValues(key);
                    for (int i = 0; i < values.Length; ++i)
                    {
                        parameterStringBuilder.AppendFormat("{0}{1}{2}{3}", HttpUtility.UrlEncode(key), NameValueSeparator, HttpUtility.UrlEncode(values[i]), PairSeparator);
                    }
                }


                if (parameters.Count > 0)
                {
                    parameterStringBuilder.Remove(parameterStringBuilder.Length - 1, 1);
                }
            }

            return parameterStringBuilder.ToString();
        }
    }
}